import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_module/common/http/YZHttp.dart';
import 'package:flutter_module/common/http/YZHttpUtils.dart' show HttpUtils;
import 'package:flutter_module/common/store/shared_preferences.dart';
import 'package:flutter_module/model/http_header_model.dart';
import '../../model/user.dart';
import '../channel/ChannelConstant.dart';


class ExtremelyRichChannel {
  static final ExtremelyRichChannel _extremelyRichChannel = ExtremelyRichChannel._internal();

  factory ExtremelyRichChannel() {
    return _extremelyRichChannel;
  }

  ExtremelyRichChannel._internal();

  static ExtremelyRichChannel get instance {
    return _extremelyRichChannel;
  }

  /// 发送消息给native
  void sendEventToNative(String key, Map<String, Object> args) {
    BoostChannel.instance.sendEventToNative(key, args);
  }

  /// 接收消息
  /// 使用方法：
  /// VoidCallback BoostChannel.instance.addEventListener("yourEventKey", (key, arguments) { }
  /// 然后在退出的时候（比如dispose中）移除监听者 removeListener?.call();
  VoidCallback addEventListener(String key, EventListener listener) {
    return BoostChannel.instance.addEventListener(key, listener);
  }

  MethodChannel? nativeConfigChannel;

  /// 监听原生配置回调
  void listenToNativeConfig() {
    nativeConfigChannel = const MethodChannel(CHANNEL_NATIVE_CONFIG);
    debugPrint('bind----listen');
    nativeConfigChannel
        ?.setMethodCallHandler((call) => initialNativeConfig(call));
  }

  initialNativeConfig(MethodCall call) {
    debugPrint('bind----init---${call.method}--${call.arguments}');
    Map<String, dynamic> map = jsonDecode(call.arguments);

    debugPrint('bind----init---map${map.toString()}');
    if (call.method == CHANNEL_NATIVE_CONFIG) {
      if (map.containsKey(KEY_USER_INFO)) {
        User user = User.fromJson(map[KEY_USER_INFO]);
        debugPrint('bind----init---user $user');

        SharedPreferences.instance.user = user;
        debugPrint('bind----token----${user.token}');
        debugPrint('bind----userStatus----${user.userStatus}');
        debugPrint('bind----KEY_USER_INFO--user--${user.toString()}');
      }
      if (map.containsKey(KEY_NETWORK_CONFIG)) {
        //网络配置
        String baseUrl = map[KEY_NETWORK_CONFIG][KEY_BASE_URL] as String;
        HttpHeaderModel headerModel =
            HttpHeaderModel.fromJson(map[KEY_NETWORK_CONFIG][KEY_HEADER]);
        SharedPreferences.instance.httpHeader = headerModel;
        debugPrint(
            'bind----KEY_NETWORK_CONFIG--headerModel--${headerModel.toString()}');
        debugPrint('bind----base_url----$baseUrl');
        debugPrint('bind----header----${headerModel.platform}');

        // 初始化request类
        HttpUtils.init(
          baseUrl: baseUrl,
        );
        // 网络例子
        // HttpUtils.get(api_circleArticle_articleDetails,
        //     successCallBack: (data) {
        //   Test test = Test.fromJson(data);
        //   debugPrint(test.toString());
        // }, errorCallBack: (e) {
        //   debugPrint(e.toString());
        // });
      }
    } else {
      debugPrint('bind----no_match_method---${call.method}');
    }
  }

  /// 发送配置到原生
  void sendToNativeConfig() async {
    // 暂时只有情况用户信息，重新登录
    final int result = await nativeConfigChannel?.invokeMethod(CHANNEL_NATIVE_CONFIG);
    debugPrint('bind----send_result---$result');
  }
}
